<?php
namespace app\admin\library\orders;
use app\common\model\Orders;
use app\common\model\OrdersItem;
use app\common\model\Goods;
use think\Db;
use think\Session;
use app\common\model\Organization;

class LibraryOrders
{
    /**
     * 获取首页数据
     */
    public function getList()
    {
        // 获取团队
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')
        ->alias('am')
        ->join('__ORGANIZATION__ o','o.id=am.organization_id')
        ->field('o.*')
        ->where('account_id',$account_id)
        ->select();

        $where = $this->buildParams();
        // 团队订单数量详情列表
        $organization_order =[];
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['id'];
            },collection($account_member)->toArray());
            $where['organization_id'] = ['in',$organization_list];
            // 获取加入的所在团队的订单数量
            foreach ($account_member as $key => $value) {
                list($total,$new_order_total,$cancel_order_total) = $this->getOrderTotal(['organization_id'=>$value['id']]);
                $order_data = [
                    'total'     =>$total,
                    'new_order_total'=>$new_order_total,
                    'cancel_order_total'=>$cancel_order_total,
                    'name' => $value['name']
                ];
                array_push($organization_order,$order_data);
            }
        }else{
            // 获取各个团队的订单数量
            $organization = Organization::select();
            foreach ($organization as $key => $value) {
                list($total,$new_order_total,$cancel_order_total) = $this->getOrderTotal(['organization_id'=>$value['id']]);
                $order_data = [
                    'total'     =>$total,
                    'new_order_total'=>$new_order_total,
                    'cancel_order_total'=>$cancel_order_total,
                    'name' => $value['name']
                ];
                array_push($organization_order,$order_data);
            }
        }
        list($total,$new_order_total,$cancel_order_total) = $this->getOrderTotal($where);
        
        $data = [
            'rows'      => $organization_order,//团队列表订单数量
            'total'     =>$total,
            'new_order_total'=>$new_order_total,
            'cancel_order_total'=>$cancel_order_total
        ];

        return $data;
        
    }
    /**
     * 获取订单数量（全部，新增，取消）
     */
    public function getOrderTotal($where){
        $total = Db::name('orders')
                    ->alias('o')
                    ->join('__ORDERS_ITEM__ oi', 'o.id = oi.order_id')
                    ->join('__GOODS__ g', 'oi.goods_id = g.id')
                    ->group('order_id')
                    ->where($where)
                    ->count();
        $new_order_total = Db::name('orders_item')
        ->alias('oi')
        ->join('__ORDERS__ o','o.id=oi.order_id')
        ->group('order_id')
        ->where($where)
        ->where('progress',1)
        ->count();
        $cancel_order_total = Db::name('orders_item')
        ->alias('oi')
        ->join('__ORDERS__ o','o.id=oi.order_id')
        ->group('order_id')
        ->where($where)
        ->where('progress',0)
        ->count();
        return [$total,$new_order_total,$cancel_order_total];
    }
    protected function buildParams()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if(!empty($where['brand_name'])){
            $where['brand_id'] = Db::name('goods_brand')->where('name', $where['brand_name'])->value('id');
            unset($where['brand_name']);
        }
        if(!empty($where['cate_name'])){
            $where['cate_id'] = Db::name('goods_categories')->where('name', $where['cate_name'])->value('id');
            unset($where['cate_name']);
        }
        if (input('progress') === '0') {
            $where['progress'] = 0;
        }
        return $where;
    }
    protected function getItemsMap(&$rows)
    {
        $oi_ids = array_column($rows, 'oi_ids');
        $oi_ids = explode(',', implode(',', $oi_ids));
        $rows_map = Db::name('orders_item')->where('id', 'in', $oi_ids)
                                        ->column('id,order_id,order_sn,goods_id,color,spec,qty,price,remarks,progress,express', 'id');

        //商品信息
        $goods_map = Db::name('goods')->where('id', 'in', array_column($rows_map, 'goods_id'))
                                    ->column('');
        $progress_desc = OrdersItem::$progress_desc;
        $size_sets = Goods::$size_sets;
        foreach($rows_map as &$row) {
            $goods_info          = $goods_map[$row['goods_id']];
            $row['goods_name']   = $goods_info['name'];
            $row['pic']          = config('upload_path') . $goods_info['picture'];
            $row['pic_tmb']      = $this->getThumb($row['pic']);
            $row['progress_txt'] = $progress_desc[$row['progress']];
            $row['can_ship']     = in_array($row['progress'], [1,2,3]);

            $size_set = $goods_map[$row['goods_id']]['size_set'];
            $row['size_set']     = explode(',', $size_sets[$size_set]);
        }
        //print_r($rows_map);
        return $rows_map;
    }
    protected function getThumb($file_path)
    {
        $parts = explode('/', $file_path);
        $file_name = array_pop($parts);

        list($name, $ext) = explode('.', $file_name);
        $thumb_path = implode('/', $parts) . '/' . $name . '_tmb.' . $ext;
        //return $thumb_path;
        if (!file_exists('../..' . $thumb_path)) {
            return $file_path;
        } else {
            return $thumb_path;
        }
    }

    public function getItemList()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])
                                                    ->value('id');
            unset($where['acct_name']);
        }
        if(!empty($where['brand_name'])){
            $where['brand_id'] = Db::name('goods_brand')->where('name', $where['brand_name'])->value('id');
            unset($where['brand_name']);
        }
        if(!empty($where['cate_name'])){
            $where['cate_id'] = Db::name('goods_categories')->where('name', $where['cate_name'])->value('id');
            unset($where['cate_name']);
        }
        if (input('progress') === '0') {
            $where['progress'] = 0;
        }
        if (input('progress') === '1-10') {
            $where['progress'] = ['in',['1','10']];
        }
        //print_r($where);
        $page = max(input('get.page',0),1);
        $page_size = 15;

        $orders_model = new Orders();
        // 获取团队 
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['organization_id'] = ['in',$organization_list];
        }
        $total = $orders_model->alias('o')->join('__ORDERS_ITEM__ oi','o.id=oi.order_id')
                                    ->join('__GOODS__ g','g.id=oi.goods_id')
                                    ->where($where)
                                    ->count();
        //return $orders_model->getLastSql();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total == 0){
            $this->success('ok','',$data);
        }

        $items = $orders_model->alias('o')->join('__ORDERS_ITEM__ oi','o.id=oi.order_id')
                            ->join('__GOODS__ g','g.id=oi.goods_id')
                            ->where($where)
                            ->field('o.id as order_id,order_no,order_sn,cust,area_path,detail_addr,o.acct_id,o.add_time,oi.id,goods_id,spec,color,qty,price,remarks,progress,g.cate_id,brand_id,name,picture')
                            ->order('o.add_time desc')
                            ->page($page,$page_size)->select()->toArray();
        if (!empty($where['progress']) && $where['progress'] == 3) {
            $this->setStock($items);
        }
        //return $orders_model->getLastSql();
        //return $items;
        $acct_ids = array_unique( array_column($items, 'acct_id') );
        $acct_map = Db::name('account')->where('id','in',$acct_ids)->column('');
        //return $acct_map;
        $progress_desc = OrdersItem::$progress_desc;
        foreach ($items as $key => $item) {
            $items[$key]['pic'] = config('upload_path') . $item['picture'];
            $items[$key]['pic_tmb'] = $this->getThumb($items[$key]['pic']);
            $items[$key]['acct_name'] = $acct_map[$item['acct_id']]['true_name'];
            $items[$key]['add_day'] = date('Y-m-d', $item['add_time']);
            $items[$key]['add_time'] = date('H:i', $item['add_time']);
            $items[$key]['progress_desc'] = $progress_desc[$item['progress']];
        } 
        //分组               
        $orders = [];
        foreach ($items as $item) {
            $orders[$item['order_no']][] = $item;
        }
        krsort($orders);
        $rows = [];
        foreach ($orders as $order_no => $items) {
            $tmp = [
                'order_no' => $order_no,
                'items'    => $items
            ];
            $rows[] = $tmp;
        }
       
        $data['rows'] = $rows;
        $this->success('成功','',$data);
    }
    /**
     * 订单明细的表头信息
     */
    public static function orderDetailAttrFactory(){
        $head_name_list = [
            'order_no'=>'订单号',
            'acct_name'=>'销售',
            'purchase_name'=>'报单员',
            'recv_day'=>'接单日期',
            'pay_type'=>'支付方式',
            'add_time'=>'提交时间',
            'cust'=>'客户',
            'phone'=>'电话',
            'detail_addr'=>'地址',
            'goods_info'=>'商品名称',
            'color'=>'颜色',
            'spec'=>'尺码',
            'qty'=>'数量',
            'purchase_price'=>'工厂价',
            'factory_price'=>'运费',
            'purchase_times'=>'报单次数',
            'price'=>'售价',
            'pack_price'=>'运费/包装',
            'stall_name'=>'档口',
            // 'exp_name'=>'物流公司',
            'exp_time' =>'发货时间',
            'exp_no'=>'物流单号',
            'remarks'=>'备注',
            'progress_txt'=>'状态'
        ];
        return $head_name_list;
    }
    /**
     * 订单明细的表头信息
     */
    public static function orderDetailAttr($have_factory_price = false){
        $head_name_list = [
            'order_no'=>'订单号',
            'acct_name'=>'销售',
            'purchase_name'=>'报单员',
            'recv_day'=>'接单日期',
            'pay_type'=>'支付方式',
            'add_time'=>'提交时间',
            'cust'=>'客户',
            'phone'=>'电话',
            'detail_addr'=>'地址',
            'goods_info'=>'商品名称',
            'color'=>'颜色',
            'spec'=>'尺码',
            'qty'=>'数量',
            'purchase_price'=>'工厂价',
            'purchase_times'=>'报单次数',
            'price'=>'售价',
            'pack_price'=>'运费/包装',
            'stall_name'=>'档口',
            // 'exp_name'=>'物流公司',
            'exp_time' =>'发货时间',
            'exp_no'=>'物流单号',
            'remarks'=>'备注',
            'progress_txt'=>'状态'
        ];
        return $head_name_list;
    }
    /**
     * 订单退货的表头信息
     */
    public static function orderReturnAttr($pur_price_rules=false){
        $head_name_list = [
            'add_time'=>'登记日期',
            'final_time'=>'退款时间',
            'order_no'=>'订单号',
            'cust'=>'客户',
            'saler'=>'销售',
            'goods_name'=>'商品名称',
            'order_qty'=>'订单数量',
            'spec'=>'尺码',
            'color'=>'颜色',
            'price'=>'单价',
            'refund_total'=>'退款金额',
            'qty'=>'退货数量',
            'reason'=>'退货原因',
            'exp_name'=>'物流名称',
            'exp_no' =>'快递单号',
        ];
        if($pur_price_rules){
            $head_name_list['pur_price'] = '报单价';
        }
        return $head_name_list;
    }
    /**
     * 订单取消的表头信息
     */
    public static function orderCancelAttr($pur_price_rules=false){
        $head_name_list = [
            'add_time'=>'登记日期',
            'final_time'=>'退款时间',
            'order_no'=>'订单号',
            'cust'=>'客户',
            'saler'=>'销售',
            'goods_name'=>'商品名称',
            'order_qty'=>'订单数量',
            'spec'=>'尺码',
            'color'=>'颜色',
            'price'=>'单价',
            'pur_price'=>'工厂价',
            'refund_total'=>'退款金额',
            // 'qty'=>'退货数量',
            'reason'=>'取消原因',
        ];
        if($pur_price_rules){
            $head_name_list['pur_price'] = '工厂价';
        }
        return $head_name_list;
    }
    /**
     * 计算订单数据
     */
    public static function getOrderData($params,$page=1,$page_size=50)
    {
        if (!empty($params['date1']) && !empty($params['date2'])) {
            $date1 = strtotime($params['date1']);
            $date2 = strtotime($params['date2']) + 24*60*60;
        } else {
            $date1 = strtotime(date('Y-m-1'));
            $date2 = time();
        }
        $where['oi.add_time'] = ['between',[$date1, $date2]];
        if (!empty($params['saler'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$params['saler'])->value('id');
        }
        if (!empty($params['cust'])) {
            $where['o.cust'] = $params['cust'];
        }
        // 只能查询所在团队数据
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['o.organization_id'] = ['in',$organization_list];
        }
        if(!empty($params['organization_id'])){
            if($params['organization_id'] == 'no_organization'&&Rules::hasRules('6')){//查询无团队数据
                $where['o.organization_id'] = null;
            }else{//查询团队数据
                $where['o.organization_id'] = $params['organization_id'];
            }
            
        }
        if(!empty($params['goods_categories_type'])){
            $where['goods_categories_type'] = $params['goods_categories_type'];
        }

        $oi_model = new OrdersItem();

        // 计算业绩
        $total_list = [];
        // 售价金额总和
        $sell_total = $oi_model->alias('oi')->join('__ORDERS__ o','order_id=o.id')->where($where)->field('sum(price*qty+pack_price) as totals')->find();
        $total_list['sell_total'] = $sell_total['totals'];
        // 退款售价金额总和
        $refund_total = $oi_model->alias('oi')->join('__ORDERS__ o','order_id=o.id')->where(['progress'=>['in',[0,5]]])->where($where)->field('sum(price*qty+pack_price) as totals')->find();
        $total_list['refund_total'] = $refund_total['totals'];

        // 报价金额总和
        $purchase_total = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty) as totals')
        ->find();
        $total_list['purchase_total'] = $purchase_total['totals'];
        // 退款报价金额总和
        $refund_purchase_total = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2],'progress'=>['in',[0,5]]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty) as totals')
        ->find();
        $total_list['refund_purchase_total'] = $refund_purchase_total['totals'];
        // 运费
        $purchase_total2 = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty+factory_price) as totals')
        ->find();
        $total_list['purchase_total2'] = $purchase_total2['totals'];
        // 退款报价金额总和
        $refund_purchase_total2 = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2],'progress'=>['in',[0,5]]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty+factory_price) as totals')
        ->find();
        $total_list['refund_purchase_total2'] = $refund_purchase_total2['totals'];
        // 计算利润
        // 售价利润
        $total_list['sell_profit'] = bcsub($sell_total['totals'],$refund_total['totals'],2);
        // 报价利润
        $total_list['purchase_profit'] = bcsub($purchase_total['totals'],$refund_purchase_total['totals'],2);
        $total_list['purchase_profit2'] = $purchase_total2['totals'] - $refund_purchase_total2['totals'];

        // 报价金额总和
        $orderNums = $oi_model->alias('oi')
        ->join('__ORDERS__ o','order_id=o.id')
        ->join('__PURCHASE__ p','p.order_item_id=oi.id')
        ->where(['p.status'=>['neq',2]])
        ->where($where)
        ->field('p.price,oi.price as oi_peice,qty')
        ->field('sum(p.price*qty) as totals')
        ->group('order_id')
        ->count();
        $total_list = [
            ['name'=>'售价+运费/包装','all'=>$total_list['sell_total'],'refund'=>$total_list['refund_total'],'total'=>$total_list['sell_profit']],
            ['name'=>'报价','all'=>$total_list['purchase_total'],'refund'=>$total_list['refund_purchase_total'],'total'=>$total_list['purchase_profit'],'orderNums' => $orderNums],
            ['name'=>'报价+运费','all'=>$total_list['purchase_total2'],'refund'=>$total_list['refund_purchase_total2'],'total'=>$total_list['purchase_profit2']]
        ];

        
    
        $data = array(
            'total_list'         => $total_list,
        );
        return $total_list;
    }
    
}